import React from 'react';
import { Card, Form, Table, Modal, message } from 'antd';
import { get as getPath } from 'object-path';
import { Pagination } from '@/components';
import { connect } from 'umi';
import { formatMessage } from 'umi';
// import { history } from 'umi';
import moment from 'moment';
import DataPick2 from '@/components/DatePicker2';
import request from '@/utils/request';
import { history } from 'umi'

class AbsenceList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            orderByField: '',
            visible: false,
            dateOption: [
                {
                    en: 'year',
                    cn: '今年'
                },
                {
                    en: 'month',
                    cn: '本月'
                },
                {
                    en: 'week',
                    cn: '本周'
                }
            ],
            times: [
                moment(
                    moment()
                        .month(moment().month())
                        .startOf('month')
                        .format('YYYY-MM-DD')
                ),
                moment()
            ],
            signDate: '',
            columnsModal: [
                {
                    title: '工号',
                    dataIndex: 'userNo',
                    key: 'userNo'
                },
                {
                    title: '打卡时间',
                    dataIndex: 'attDatetime',
                    key: 'attDatetime'
                },
                {
                    title: '考勤来源',
                    dataIndex: 'deviceName',
                    key: 'deviceName'
                }
            ],
            sorters: ''
        };
    }

    componentDidMount() {
        const { times } = this.state;
        if (getPath(this.props, 'date')) {
            const date = [
                moment(
                    moment(getPath(this.props, 'date'))
                        .startOf('month')
                        .format('YYYY-MM-DD')
                ),
                moment(
                    moment(getPath(this.props, 'date'))
                        .endOf('month')
                        .format('YYYY-MM-DD')
                )
            ];
            this.handleSearch(date);
        } else {
            this.handleSearch(times);
        }
    }

    componentWillUnmount() {
        const { dispatch, abnormal } = this.props;

        dispatch({
            type: 'abnormal/save',
            payload: {
                paginationAbsence: {
                    ...abnormal.paginationAbsence,
                    current: 1,
                    pageSize: 10
                }
            }
        });
    }

    handleSearch = (v, type) => {
        this.setState(
            {
                times: v
            },
            () => {
                this.fetchList(getPath(type, ''));
            }
        );
    };

    showModal = () => {
        this.setState({
            visible: true
        });
    };

    setVisible = type => {
        this.setState({
            visible: type
        });
    };

    // 获取列表
    fetchList = type => {
        const { times } = this.state;
        const {
            dispatch,
            abnormal: { paginationAbsence }
        } = this.props;
        // const user = JSON.parse(localStorage.getItem('user'));
        const parame = {
            startTime: times[0].format('YYYY-MM-DD'),
            endTime: times[1].format('YYYY-MM-DD'),
            pageNo: type ? 1 : paginationAbsence.current,
            pageSize: paginationAbsence.pageSize,
            orderByField: getPath(this.state, 'orderByField', '')
        };
        dispatch({
            type: 'abnormal/fetchAbcense',
            payload: parame
        });
    };

    // 表格表头点击切换排序
    changeTable = async (pagination, filters, sorter) => {
        const { sorters } = this.state;
        let orderBy;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'exceptionDate') {
                sorterField = 'exception_date';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
            this.setState({
                orderByField: orderBy
            });
        } else {
            this.setState({
                orderByField: ''
            });
        }
        const { dispatch, abnormal } = this.props;
        await dispatch({
            type: 'abnormal/save',
            payload: {
                paginationAbsence: {
                    ...abnormal.paginationAbsence,
                    ...pagination
                }
            }
        });
        if (sorter && sorters !== sorter) {
            this.setState({
                sorters: sorter
            });
            await dispatch({
                type: 'abnormal/save',
                payload: {
                    paginationAbsence: {
                        ...abnormal.paginationAbsence,
                        current: 1
                    }
                }
            });
        }
        this.fetchList();
    };

    goTo = async () => {
        const classificationRes = await request(
            `/api/workflowweb/processinstance/v1/getByAdvancedSettingType?classification=LeaveApply&companyId=${this?.props?.user?.currentUser?.companyId}`
        );

        if (classificationRes?.code === 10000) {
            history.push(
                `/personal/portal/apply?id=${classificationRes?.data?.actProcessDefinitionId}&name=${classificationRes?.data?.processName}`
            );
        } else {
            message.error(classificationRes.msg);
        }
    };

    // 打卡记录
    seeDetail = record => {
        const { dispatch } = this.props;
        const user = JSON.parse(localStorage.getItem('user'));
        const parame = {
            employeeCode: getPath(user, 'employeeCode', ''),
            startTime: moment(record.exceptionDate).format('YYYY-MM-DD'),
            endTime: moment(record.exceptionDate).format('YYYY-MM-DD'),
            pageNo: 1,
            pageSize: 10
        };
        dispatch({
            type: 'abnormal/fetchMydetail',
            payload: parame
        }).then(() => {
            this.setState({
                signDate: moment(record.exceptionDate).format('YYYY-MM-DD')
            });
            this.showModal();
        });
    };

    render() {
        const { loading, abnormal } = this.props;
        const { absenceData, paginationAbsence, attenddetail } = abnormal;
        const { dateOption, signDate, columnsModal, visible } = this.state;

        const columnsAbsence = [
            {
                title: `${formatMessage({
                    id: 'stat.absence.all'
                })}`,
                dataIndex: 'typeNcik',
                key: 'typeNcik',
                render: () => (
                    <span>
                        {formatMessage({
                            id: 'stat.absence.type'
                        })}
                    </span>
                )
            },
            {
                title: `${formatMessage({
                    id: 'stat.absence.exceptionDate'
                })}`,
                dataIndex: 'exceptionDate',
                key: 'exceptionDate',
                render: (text, record) => <span>{record.exceptionDate}</span>,
                sorter: () => {}
            },
            {
                title: `${formatMessage({
                    id: 'stat.absence.action'
                })}`,
                dataIndex: 'action',
                key: 'action',
                width: '40%',
                render: (text, record) => (
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'flex-start'
                        }}
                    >
                        <a onClick={() => this.seeDetail(record)}>
                            {formatMessage({
                                id: 'stat.absence.seeDetail'
                            })}
                        </a>
                        {/* <a
                                href="#"
                                style={{ marginLeft: '20px' }}
                                onClick={e => {
                                    e.preventDefault();
                                    history.push({
                                        pathname:
                                            '/personal/flow/mine/list/apply',
                                        query: {
                                            templateId: record.templateId,
                                            processDeploymentId:
                                                record.processDeploymentId,
                                            formDeploymentId:
                                                record.formDeploymentId,
                                            templateName: record.templateName,
                                            id: ''
                                        }
                                    });
                                }}
                            >
                                {formatMessage({
                                    id: 'stat.absence.toApply'
                                })}
                            </a> */}
                        <a onClick={() => this.goTo(record)} style={{ marginLeft: '20px' }}>
                            {formatMessage({
                                id: 'stat.absence.toApply'
                            })}
                        </a>
                    </div>
                )
            }
        ];

        return (
            <Card
                title={formatMessage({
                    id: 'stat.absence.cardtitle'
                })}
                headStyle={{ padding: 0 }}
                bodyStyle={{ padding: '30px 0' }}
                bordered={false}
                extra={
                    <DataPick2
                        onSearch={v => {
                            this.handleSearch(v, true);
                        }}
                        dateOption={dateOption}
                        mode="month"
                        defaultDate={getPath(this.props, 'date')}
                    />
                }
            >
                <Table
                    bordered={false}
                    dataSource={absenceData}
                    columns={columnsAbsence}
                    loading={loading}
                    scroll={{ x: 'max-content' }}
                    rowKey="id"
                    onChange={this.changeTable}
                    pagination={false}
                />
                <Pagination {...paginationAbsence} onChange={this.changeTable} loading={loading} />
                <Modal
                    title={
                        <div>
                            <div style={{ fontSize: '20px', color: '#333' }}>
                                {formatMessage({
                                    id: 'stat.ckdkjl'
                                })}
                            </div>
                            <p
                                style={{
                                    color: 'rgba(0, 0, 0, .45)',
                                    fontSize: '14px',
                                    marginBottom: 0
                                }}
                            >
                                {signDate}
                                {formatMessage({
                                    id: 'stat.dksj'
                                })}
                            </p>
                        </div>
                    }
                    width={600}
                    footer={null}
                    visible={visible}
                    onOk={() => this.setVisible(false)}
                    onCancel={() => this.setVisible(false)}
                    centered
                >
                    <Table
                        dataSource={attenddetail}
                        columns={columnsModal}
                        pagination={false}
                        loading={loading}
                        rowKey="id"
                    />
                </Modal>
            </Card>
        );
    }
}

export default connect(({ abnormal, user, loading }) => ({
    user,
    abnormal,
    loading: loading.models.abnormal
}))(Form.create()(AbsenceList));
